package m.olive.data.service;

import java.util.ArrayList;
import java.util.List;

import m.framework.dao.mapping.SqlType;
import m.framework.dao.selector.Query;
import m.framework.exception.ValidateError;
import m.framework.service.BaseService;
import m.framework.utils.BeanUtil;
import m.framework.utils.StringUtil;
import m.olive.data.model.DatasourceInfo;
import m.olive.data.model.DsParam;
import m.olive.data.model.DsParamDto.ParamType;

import org.springframework.stereotype.Component;

@Component
public class DatasourceInfoService extends BaseService{

	public void insertDatasourceInfo(DatasourceInfo datasourceInfo, List<DsParam> out) {
		List in=parseCommand(datasourceInfo.getDatasourceInfoId(), datasourceInfo.getAccessCommand());
		baseDao.insert(datasourceInfo);
		baseDao.insertList(in);
		baseDao.insertList(out);
	}

	
	//解析出入参
	private List<DsParam> parseCommand(String dsId,  String command){
		List list=new ArrayList();
		List<String> param=StringUtil.pickUp(command, "<([^<]|[^>]*)>");
		int index=0;
		for(String str:param){
			if(str.length()==2){
				throw new ValidateError("无法解析参数:"+str+",请确认参数是否只包含字符数字和下划线");
			}
			String pa=str.substring(1,str.length()-1);
			if(pa.replaceAll("\\w+", "").length()!=0){
				throw new ValidateError("无法解析参数:"+str+",请确认参数是否只包含字符数字和下划线");
			}
			DsParam dp=new DsParam();
			dp.setPk();
			dp.setDatasourceInfoId(dsId);
			dp.setParamCode(pa);
			dp.setParamIndex(index);
			dp.setParamType(ParamType.入参);
			list.add(dp);
			index++;
		}
		return list;
	}


	public DatasourceInfo getDatasourceInfo(String pk) {
		DatasourceInfo df=baseDao.get(DatasourceInfo.class, pk);
		super.initList(df,"dsParams","paramIndex");
		return df;
	}


	public void deleteDatasourceInfo(DatasourceInfo datasourceInfo) {
		Query q=Query.forClass(DsParam.class);
		q.eq("datasourceInfoId", datasourceInfo.getDatasourceInfoId());
		baseDao.executeSql(q, SqlType.DELETE);
		
		baseDao.delete(datasourceInfo);
	}


	public void updateDatasourceInfo(DatasourceInfo datasourceInfo, List<DsParam> param) {
		List<DsParam> dbList=super.initList(datasourceInfo,"dsParams","paramIndex");
		for(DsParam db:dbList){
			for(DsParam page:param){
				if(db.getDsParamId().equals(page.getDsParamId())){
					BeanUtil.copyIgnoreNull(page, db);
				}
			}
		}
		baseDao.updateNotNull(datasourceInfo);
		baseDao.updateList(dbList);
	}
}
